//
//  MyCodeViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/27.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyCodeViewController.h"
#import "MycodeCollectionViewCell.h"
#import "CodeExchangeViewController.h"
#import "ActivityDetailViewController.h"
#import "WebDetailInfoViewController.h"
#import "VIPWebViewController.h"
static NSString * cellIndentifier = @"MycodeCollectionViewCell";
@interface MyCodeViewController ()<DYQBannerScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) DYQBannerScrollView *bannerScrollView;//广告栏
@property (nonatomic,strong)  NSMutableArray  *bannerArray;

@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property(nonatomic,strong)NSMutableArray * codeGoodsArray;
@property(nonatomic,assign)CGFloat offSet;

@end

@implementation MyCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageArray = [NSMutableArray array];
    _pageNO =  1;
    _codeGoodsArray = [NSMutableArray array];
    _bannerArray = [NSMutableArray array];

    [self initViewLayout];
    [self getAdvertiseBanner];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    self.scroView.frame =CGRectMake(0, 64*VerticalRatio(),320*VerticalRatio(), 504*VerticalRatio()-49);
    _scroView.contentSize = CGSizeMake(320, 596);
    _scroView.delegate = self;
    //广告栏
    self.bannerScrollView = [[DYQBannerScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 140), NO)];
    self.bannerScrollView.backgroundColor = [UIColor clearColor];
    self.bannerScrollView.pageControlPosition = PageControlPositionCenter;
    self.bannerScrollView.noDataPlaceholderImage = [UIImage imageNamed:@"cover_cy"];
    self.bannerScrollView.timeInterval = 3;
    self.bannerScrollView.pageControllerTintColor = [UIColor whiteColor];
    self.bannerScrollView.pageControllerCurrentColor = [UIColor orangeColor];
    
    [self.scroView addSubview:_bannerScrollView];
    
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 1*VerticalRatio();
    flowLayout.minimumLineSpacing = 1*VerticalRatio();
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.userInteractionEnabled=YES;
    [self.collectionView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellWithReuseIdentifier:cellIndentifier];
    self.collectionView.alwaysBounceVertical = YES;
    

}

#pragma mark == 积分活动
- (IBAction)codeActivity:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyCodeStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"IntegralActivity"];
    [self.navigationController   pushViewController:page animated:YES];
}
#pragma mark == 积分排行
- (IBAction)codeRank:(id)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
        return;
    }else{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyCodeStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CodeRank"];
    [self.navigationController   pushViewController:page animated:YES];
    }
}
#pragma mark == 积分规则
- (IBAction)codeRule:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"VIPServiceStoryboard" bundle:nil];
    VIPWebViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"VIPWeb"];
    page.url = SX_memberScoreRule;
    page.titleStr = @"积分规则";
    [self.navigationController  pushViewController:page animated:YES];
}
#pragma mark == 我的积分
- (IBAction)myCode:(id)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
        return;
    }else{
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyCodeStoryboard" bundle:nil];
            UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PersonCode"];
            [self.navigationController   pushViewController:page animated:YES];
    }
}
#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryMallADDData" forKey:@"method"];
    [dic setObject:@"1" forKey:@"position"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_ADBanner withHttpType:@"POST" withTag:SX_kADBannerTag];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }];
    // 马上进入刷新状态
    [self.scroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.codeGoodsArray.count == _totle) {
        [self.collectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }
    
}
- (void)getIndentsList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppIntegralMall withHttpType:@"POST" withTag:SX_SX_queryAppIntegralMall];
    
}



#pragma mark----DYQBannerScrollViewDelegate

-(void)bannerScrollView:(DYQBannerScrollView *)bannerScrollView didSelectItemAtIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    WebDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebDetailInfo"];
    page.objectId = _bannerArray[index][@"appAdertUrl"];
    page.titleStr = @"详情";
    page.meType = @"4";
    [self.navigationController  pushViewController:page animated:YES];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _collectionView || scrollView== _scroView) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _collectionView || scrollView == _scroView ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_scroView setContentOffset:CGPointMake(0, 140*VerticalRatio()) animated:YES];
            _scroView.scrollEnabled = NO;
            _collectionView.scrollEnabled = YES;
        }else{
            if (scrollView == _scroView) {
                [_scroView setContentOffset:CGPointMake(0, 0) animated:YES];
                _scroView.scrollEnabled = YES;
                _collectionView.scrollEnabled = NO;
            }else{
                if (decelerate == YES) {
                    [_scroView setContentOffset:CGPointMake(0, 0) animated:YES];
                    _scroView.scrollEnabled = YES;
                    _collectionView.scrollEnabled = NO;
                }
            }
            
        }
    }
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

        return _codeGoodsArray.count;
   
    
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    return CGSizeMake(158*VerticalRatio(), 135*VerticalRatio());

}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0, 1*VerticalRatio(), 1*VerticalRatio());
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

        MycodeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
    NSString * code = [NSString stringWithFormat:@"%@",_codeGoodsArray[indexPath.row][@"integral"]];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",@"积分",code]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.180 blue:0.082 alpha:1.000] range:NSMakeRange(2,code.length)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20*VerticalTexeRatio()] range:NSMakeRange(2, code.length)];
    
    cell.codeNumber.attributedText = str;
    
    
    NSString * image = _codeGoodsArray[indexPath.row][@"imgUrl"];
    if (image.length>0) {
        [cell.codeImage sd_setImageWithURL:[NSURL URLWithString:image]];
    }else{
        cell.codeImage.image =[UIImage imageNamed:@"photos1"];
    }

    cell.codeName.text = [NSString stringWithFormat:@"%@",_codeGoodsArray[indexPath.row][@"goodsName"]];
    
    return cell;
    

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

//        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyCodeStoryboard" bundle:nil];
//        CodeExchangeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CodeExchange"];
//        page.goodsId = _codeGoodsArray[indexPath.row][@"goodsId"];
//        [self.navigationController   pushViewController:page animated:YES];
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ActivityDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ActivityDetail"];
    page.objectId = _codeGoodsArray[indexPath.row][@"goodsId"];
    page.titleStr = @"积分商品详情";
    [self.navigationController  pushViewController:page animated:YES];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_scroView.header endRefreshing];
    [_collectionView.footer endRefreshing];
    if (tag==SX_SX_queryAppIntegralMall){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.collectionView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.codeGoodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.codeGoodsArray addObject:entity];
                }
                _collectionView.dataSource = self;
                _collectionView.delegate = self;
                [_collectionView reloadData];
                
            });
            
            
        }
    }else if (tag==SX_kADBannerTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [self.imageArray removeAllObjects];
            //            self.imageArray = database[@"result"];
            for (NSDictionary *data in database[@"result"]) {
                [_bannerArray addObject:data];
                NSString * picture = [Common stringFromData:data[@"appAdertImagUri"]];
                [self.imageArray addObject:picture];
            }
            _bannerScrollView.imageUrls = _imageArray;
            _bannerScrollView.delegate = self;
        }
        
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
